<?php
namespace structure\components;

class Field extends \components\Component
{
	private $formName = "";
	private $fieldName = "";
	private $field = array();

	public function Start()
	{
		$component = $this->GetComponent();

		$this->formName = $component->GetAttribute("form");

		if($component->AttributeExists("label"))
		{
			$this->fieldName = $component->GetAttribute("label");
			$this->field = $this->GetField();

			$el = core("Html")->CreateElement("label", $this->field['label']);
			$el->addAttribute("for", $this->fieldName);

			return $el->Build();
		}

		$this->fieldName = $component->GetAttribute("field");
		$this->field = $this->GetField();

		return $this->BuildField();
	}

	private function BuildField()
	{
		$f = $this->field;

		$el = core("Html")->CreateElement($f['tag'], $f['content']);

		$el->AddAttribute('name', $f['name']);

		$el->AddAttribute('id', $f['name']);
		$el->AddAttribute('accept', $f['accept']);
		$el->AddAttribute('type', $f['type']);

		$el->AddAttribute('value', $f['value']);
		$el->AddAttribute('size', $f['size']);
		$el->AddAttribute('maxlength', $f['maxlength']);
		$el->AddAttribute('tabindex', $f['tabindex']);
		$el->AddAttribute('focus', $f['focus']);
		$el->AddAttribute('rows', $f['rows']);
		$el->AddAttribute('cols', $f['cols']);
		$el->AddAttribute('class', $f['class']);
		$el->AddAttribute('style', $f['style']);

		(int)$f['checked'] AND $el->AddAttribute('checked', "checked");
		(int)$f['multiple'] AND $el->AddAttribute('multiple', "multiple");
		(int)$f['readonly'] AND $el->AddAttribute('readonly', "readonly");
		(int)$f['disabled'] AND $el->AddAttribute('disabled', "disabled");

		return $el->Build();
	}

	private function GetField()
	{
		if (!empty($this->field))
		{
			return $this->field;
		}


		$field = $this->field = service("db")->Reset()->
		Select("_forms_fields.*", "_languages_content.ru as label")->
		From("_forms_fields")->
		Join("_forms_stack", "INNER")->
		On("_forms_stack.field", "=", "_forms_fields.id")->
		Join("_forms", "INNER")->
		On("_forms.id", "=", "_forms_stack.form")->
		Join("_languages_content", "INNER")->
		On("_languages_content.id", "=", "_forms_fields.label")->
		Where("_forms.name", "=", "?")->
		Where("_forms_fields.?#", "=", "?", "AND")->
		Fetch("row")->
		Placeholders($this->formName, "name", $this->fieldName)->
		Run();

		//Placeholders for: Select, On, Where



		return $field;
	}
}